"""
====================================================================
Copyright (C) 2012-2013 Eric Blond

This file is part of Neptune.

Neptune is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Neptune is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Neptune.  If not, see <http://www.gnu.org/licenses/>.
====================================================================

Created on Dec 9, 2012

@author: Eric
"""

import wx
from ..nucleus import public as nucleus
from . import context

#######

class MenuBar(nucleus.Page):
    
    def _on_Menus_change(self, old_value, new_value):
        old_menus = set([y for (_, y) in old_value])
        new_menus = set([y for (_, y) in new_value])
        for menu in new_menus - old_menus:
            menu._create(self._Context)
        old_len = len(old_value)
        new_len = len(new_value)
        for i in xrange(max(old_len, new_len)):
            if (i >= old_len) and (i < new_len):
                self._WxMenuBar.Append(new_value[i][1]._WxMenu, new_value[i][0])
            elif (i < old_len) and (i >= new_len):
                self._WxMenuBar.Remove(new_len)
            elif old_value[i] != new_value[i]:
                self._WxMenuBar.Replace(i, new_value[i][1]._WxMenu, new_value[i][0])
        for menu in old_menus - new_menus:
            menu._destroy()

    @nucleus.cell(settable = True, on_change = '_on_Menus_change')
    def Menus(self):
        return []
    
    _Context   = None
    _WxMenuBar = None
    
    def _create(self, ctx):
        self._Context = context.Context(Parent = ctx, Instance = self)
        self._WxMenuBar = wx.MenuBar()
        self._on_Menus_change([], self.Menus)
    
    def _destroy(self):
        self._on_Menus_change(self.Menus, [])
        self._WxMenuBar.Destroy()
        self._WxMenuBar = None
        self._Context = None
